 import React from 'react'
 // ===================================================================== Temp
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
// ===================================================================== global declare
const { $fn, $Lazy, $http } = window
// ===================================================================== Lazy
const Page 		= $Lazy.load(()=>import('#tp/page/page-container'))
const Form 		= $Lazy.hook(()=>import('@antd/form/layout/form'))
const Button 	= $Lazy.load(()=>import('@antd/button'))
const FormItem 	= $Lazy.load(()=>import('#private/component/form/submit-item'))
const Title 	= $Lazy.load(()=>import('#tp/title/title-small'))
const message 	= $Lazy.file(()=>import('@antd/message'))

// ===================================================================== component
class Index extends React.Component{
 	state = {
		selectedKeys:[],
		selectedRows:[],
 		spec_codes:[],
		data: [],
		sdata:{},
 	}
	// 表格
	cols = [
		{ title: '行号',			dataIndex: 'index', 				width:100 },
		{ title: '条码号', 			dataIndex: 'spec_code', 		...$fn.table.spec_code },
		{ title: '科室', 			dataIndex: 'job_name', 			width:100 },
		{ title: '岗位', 			dataIndex: 'project_name', 		width:100 },
		{ title: '状态', 			dataIndex: 'spec_status', 		width:100, render: text => +text === 1 ? '已上架':'未上架' }
	]
	// 解析条码
	getSpec(data){
		const arr = data.indexOf(',') >= 0 ? data.split(',') : data.split(/[\s\n]/)
		const stack = []
		arr.forEach(v => {
			if(!isNaN(+v) && (v.length === 12 || v.length === 14) ){
				stack.push(v)
			}
		})
		const spec_codes = Array.from(new Set(stack))
		this.setState({ spec_codes })
		return spec_codes
	}
	// 搜索标本架
	onSearch = async ({ sf_number }) => {
		if(!$fn.isValid(sf_number)) return message.then(f=>f.warning('请输入标本架'))
		const sdata = await $http.submit(this,'shelf/use',{ param:{ sf_code: sf_number  }, onError:()=> this.setState({ sdata: {} })  })
		this.setState({ sdata })
	}
	// 生成条码
	onSubmit = refresh => {
		const { spec_codes } = this.state
		if($fn.hasArray(spec_codes)){
			$http.submit(this,'shelf/validshelfbatch', { param:{ spec_codes: String(spec_codes.join('\\n')) }}).then(data=>{
				if(!refresh){
					message.then(f=>f.success('校验成功'))
				}
				data.forEach( (v,i) => v.index = i + 1 )
				this.setState({ data })
			})
		}else{
			message.then(f=>f.warning('条码不符合规范，请检查'))
		}
		$fn.clearKeys.call(this)
	}
	
	// 上架完成
	onPutAway = () => {
		const sf_number = this.specRef.getName('sf_number')
		if(!sf_number){
			return message.then(f=>f.warning('请输入标本架'))
		}
		const { selectedRows } = this.state
		$http.submit(this,'shelf/upshelfbatch', { param:{ data:JSON.stringify(selectedRows), sf_number }}).then(data=>{
			message.then(f=>f.success(`上架数量：${data?.up_num}; 上架成功数量：${data?.up_success_num}`))
			this.onSubmit(true)
		})
	}
	
	// 操作按钮
	controls = () => [
		Controls.click.call(this,'清空', ()=>{ 
			$fn.clearKeys.call(this)
			this.setState({ data:[] })
		}, { disabled: !$fn.hasArray(this.state.data) }),
		Controls.click.call(this,'删除', ()=>{
			this.setState(({ data, selectedKeys }) => {
				data.forEach( (v,i) =>{
					selectedKeys.forEach( m => {
						if( v.uuid === m ){
							data[i] = null
						}
					})
				})
				data = data.filter( v => v !== null)
				return { data, selectedKeys:[], selectedRows:[] }
			} )
		}, { isKeys:true }),
	]
	
 	render(){
		const { sdata, data, spec_codes, submitLoading, spec, selectedKeys } = this.state
 		return (
 			<Page nobc title='标本批量上架'>
				<Form onRef={ref=>this.specRef=ref} onSubmit={this.onSearch} className='submit-form small-form fxm bcf' style={{padding:20}} dir='x'>
					<FormItem tit='标本架' name='sf_number' width={300} disabled={submitLoading} onEnter={this.onSearch} r onChange={ spec => {
						this.setState({ spec })
					} }/>
					<Button label='查询' size='middle' className='ml10' onClick={()=>this.specRef.submit()} disabled={submitLoading || !spec}/>
					<dl className='fx g6 f12 ml20'>
						<dt>标本架编号：<b className='c0'>{sdata.sf_number}</b></dt>
						<dt className='mlr20'>科室：<b className='c0'>{sdata.project_name}</b></dt>
						<dt>容量：<b className='c0'>{sdata.total_capacity}</b></dt>
					</dl>
				</Form>
 				<Form onRef={ref=>this.form=ref} className='ex fv' onSubmit={this.onSubmit}>
					<div className='fx ex'>
						<div className='ex mr5 fv'>
							<Title title='条码录入' prefix={<div className='f12 ex ml15'>共计 <b className='c0'>{spec_codes.length}</b> 条</div>} />
							<FormItem wrapClassName='ex textarea-full bcf fv' style={{padding:'5px 5px 0'}} p='请输入条码' inputStyle={{height:'100%'}} name='spec' r mode='textarea' disabled={submitLoading} onChanged={({value})=> this.getSpec(value)}/>
							<div className='fxc bcf ptb5'><Button size='middle' label='校验' onClick={()=>{ this.mod = false; this.form.submit() }} disabled={submitLoading || !$fn.hasArray(spec_codes)}/></div>
						</div>
						{/* 表格 */}
						<div className='fv ex'>
							<Title title='条码列表' controls={this.controls()}/>
							<div className='fv ex bcf' style={{padding:'5px 5px 0'}}>
								{ 
									Table.call(this, { wrapClassName:' ', space:' ',
										onDisabled: ({ spec_status }) => ( { disabled: +spec_status === 1 }),
										onRowClass: ({ spec_status }) => {
											if(+spec_status === 1){	// 未能在检测中心匹配到相应数据
												return 'row-gray'
											}
										}
									}) 
								}
							</div>
							<div className='fxc bcf ptb5'><Button size='middle' disabled={!$fn.hasArray(data) || !$fn.hasArray(selectedKeys)} label='上架完成' onClick={this.onPutAway} loading={submitLoading} /></div>
						</div>
					</div>
				</Form>
 			</Page>
 		)
 	}
 }
 
 export default Index